package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceimpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Override
    public ResponseResult login(WmUserDto dto) {
        //参数校验
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //根据用户名查询
        WmUser wmUser = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        //判断该用户是否存在
        if (wmUser == null || wmUser.getStatus() != 9) {
            throw new CustomException(AppHttpCodeEnum.USER_INEXISTENCE);
        }

        String password = wmUser.getPassword();

        String passwordRes = MD5Utils.encodeWithSalt(dto.getPassword(), wmUser.getSalt());
        //判断密码是否正确
        if (!password.equals(passwordRes)) {
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //返回jwt结果
        Map<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(wmUser.getId().longValue()));
        wmUser.setPassword("");
        wmUser.setSalt("");
        map.put("user", wmUser);
        return ResponseResult.okResult(map);
    }
}
